import type { FormRules } from 'element-plus';
import { type EditPasswordRequest, type UserInfo, editMyInfoAxios } from '@/api/login';

export type EditPasswordForm = EditPasswordRequest & { affirmPassword: string };

/** 修改用户资料 */
export function useEditUserInfo(userInfo: UserInfo) {
  const editUserInfoFrom = reactive<UserInfo>(userInfo);
  const restImageCropperRef: $RefComp<'RestImageCropper'> = ref(null);
  const editUserInfoFormRef: $RefComp<'ElForm'> = ref(null);
  const editUserInfoLoading = ref(false);
  const realnameMin = 2;
  const realnameMax = 36;
  const editUserInfoRules: FormRules = {
    realname: [
      { required: true, type: 'string', message: '请输入真实姓名', trigger: ['blur', 'change'] },
      { min: realnameMin, max: realnameMax, type: 'string', message: `真实姓名长度在 ${realnameMin} 到 ${realnameMax} 之间`, trigger: ['blur', 'change'] },
    ],
    sex: [
      { required: true, type: 'number', message: '请选择性别', trigger: ['blur', 'change'] },
      { min: 1, max: 2, type: 'number', message: `性别不合法`, trigger: ['blur', 'change'] },
    ],
  };

  /** 打开裁剪框 */
  function openCropper(files: File[]): Promise<File[]> {
    return new Promise((resolve, reject) => {
      const file = files[0];
      if (file) {
        restImageCropperRef.value?.show({
          file,
          croppedCanvasOptions: {
            fillColor: '#ffffff',
            maxWidth: 240,
            maxHeight: 240,
          },
          fail: () => {
            reject(null);
          },
          success: (res: File) => {
            resolve([res] as File[]);
          },
        });
      } else {
        resolve(files);
      }
    });
  }

  /** 修改用户信息 */
  async function submitEditUserInfo() {
    try {
      await editUserInfoFormRef.value?.validate();
      try {
        editUserInfoLoading.value = true;
        const data = { realname: editUserInfoFrom.realname, avatar: editUserInfoFrom.avatar, sex: editUserInfoFrom.sex };
        await editMyInfoAxios(data);
        editUserInfoLoading.value = false;
        useUserStore().setUserInfo({ ...userInfo, ...data });
        ElToast.success('修改成功');
      } catch (error) {
        editUserInfoLoading.value = false;
        ElToast.error(error.msg || '提交失败，-BD003');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD001');
    }
  }

  return {
    submitEditUserInfo,
    editUserInfoFormRef,
    editUserInfoLoading,
    editUserInfoFrom,
    realnameMin,
    realnameMax,
    restImageCropperRef,
    editUserInfoRules,
    openCropper,
  };
}
